<?php
class FunctionApp{
	static function getAppDirectory($appid){
		$session_var = "App_Directory_".$appid;
		if(isset( $_SESSION[ $session_var ] )){
			return $_SESSION[ $session_var ] ;
		}else{
			$appinfo = FunctionData::readApp($appid);
			if($appinfo!=null){
				$directory = $appinfo->getDirectory();
				$_SESSION[ $session_var ]  = $directory;
				return $_SESSION[ $session_var ] ;
			}else{
				{Error::getInstance() ->addError( 12  , "Request invalid application id!" );} ;
			}
		}
	}
	static function createApp($name,$directory){
		$rs = new Result();
		if((Session::getRoleOfArea( "ApplicationManagement"  ) >=  (3)  ) ){
			$id = FunctionData::registerAnAppId();
			$app_mng = FunctionData::readAppManager();
			$app_mng->addApp($id,$name);
			FunctionData::writeAppManager($app_mng);
			$app = new DataApp();
			$app->setName($name);
			$app->setDirectory($directory);
			FunctionData::writeApp($id,$app);
			$rs->addData("Successfull","Create App Successful please save follow infomation.!");
			$rs->addData("id",$id);
			$rs->addData("Secret key",$app->getSecretKey());
		}else{
			{Error::getInstance() ->addError( 16  , "Action not allow!"  );} ;
		}
		return $rs;
	}
	static function addStaticKey($appid,$key){
		echo "Functionapp:addStatickey:".$key."\n";
		$app = FunctionData::readApp($appid);
		if($app != null){
			$app->addStaticKey($key);
			FunctionData::writeApp($appid,$app);
		}
	}
	static function addUserKey($appid, $key){
		$app = FunctionData::readApp($appid);
		if($app != null){
			$app->addUserKey($key);
			FunctionData::writeApp($appid,$app);
		}
	}
	static function getStaticKey($appid,$key){
		$full_key = "apps_" .$appid."_".$key;
		return FunctionData::readKey($full_key);
	}
	static function getUserKey($appid,$userid,$key){
		$full_key = "apps_user_" .$appid."_".$userid."_".$key;
		return FunctionData::readKey($full_key);
	}
	static function setStaticKey($appid, $key,$bytes){
		$full_key = "apps_" .$appid."_".$key;
		FunctionData::writeKey($full_key,$bytes);
	}
	static function setUserKey($appid,$userid,$key,$bytes){
		$full_key = "apps_user_" .$appid."_".$userid."_".$key;
		FunctionData::writeKey($full_key,$bytes);
	}
	static function incStaticKey($appid, $key){
		$full_key = "apps_" .$appid."_".$key;
		FunctionData::incKey($full_key);
	}
	static function incUserKey($appid,$userid,$key){
		$full_key = "apps_user_" .$appid."_".$userid."_".$key;
		FunctionData::incKey($full_key);
	}
}
?>